import React, { Component } from 'react'
import { connect } from 'react-redux'
import { VoicePlayer, cloneDeep, Type } from '@utils/Global'
import { ReplayAction } from '@act'
import { Storage, Keys } from '@utils/LocalStorage'

class VoiceItem extends Component {
  clickItem = () => {
    const { item: { voiceStatus }, dispatch, url } = this.props
    const { updateVoiceStatus, stopAllVoice } = ReplayAction
    let status = null
    if (voiceStatus.playing || voiceStatus.loading) {
      status = this.setVoiceStatus(false, false, false, true)
      dispatch(updateVoiceStatus({url, status, type: 'voice'}))
      VoicePlayer.stop()
      return
    }
    dispatch(stopAllVoice())
    status = this.setVoiceStatus(true, false, false, true)
    dispatch(updateVoiceStatus({url, status, type: 'voice'}))
    this.setVoiceHasPlayed()
    VoicePlayer.play(url, () => {
      status = this.setVoiceStatus(false, true, false, true)
      dispatch(updateVoiceStatus({url, status, type: 'voice'}))
    }, () => {
      status = this.setVoiceStatus(false, false, false, true)
      dispatch(updateVoiceStatus({url, status, type: 'voice'}))
    })
  }
  setVoiceStatus = (loading = false, playing = false, error = false, hasPlayed = true) => {
    return {
      loading: loading,
      playing: playing,
      error: error,
      hasPlayed: hasPlayed
    }
  }
  setVoiceHasPlayed() {
    const { url } = this.props
    const playedList = Storage.read(Keys.QA_VOICE_KEY) || []
    if (playedList.indexOf(url) < 0) {
      playedList.push(url)
      Storage.save(Keys.QA_VOICE_KEY, playedList)
    }
  }
  setWidth() {
    const { time } = this.props
    const _time = Math.ceil(time / 1000)
    const point = parseFloat(_time / 60) + 1
    return (30 + 70) * point + 'px'
  }
  renderStatus() {
    const { item: { voiceStatus } } = this.props
    if (!voiceStatus.hasPlayed) {
      return <div className="red_point"></div>
    } else if (voiceStatus.loading) {
      return (
        <div className="voice_loading">
          <img className="voice_loading_icon" src={require('@images/indicator_verybig.gif')} alt=""/>
        </div>
      )
    } else {
      return null
    }
  }
  render() {
    const { time, item: { voiceStatus } } = this.props
    const _time = Math.ceil(time / 1000)
    const _src = voiceStatus.playing ? require('@images/question/voice_icon_animate.gif') : require('@images/question/voice_icon.png')
    return (
      <div onClick={this.clickItem} className="qa_voice" style={{ width: this.setWidth() }}>
        <img className="voice_icon" src={_src} />
        <div className="triangle"></div>
        <div className="time"> { _time }" </div>
        {this.renderStatus()}
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return { qaList: state.ReplayState.qa.list }
}

export default connect(mapStateToProps)(VoiceItem)
